<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import myAxios from "../plugins/MyAxios.ts"
import {Toast} from "vant";
import type {UserType} from "../models/user";
import {getCurrentUser} from "../service/user.ts";

const route = useRoute();
const router = useRouter();
//获取当前登录的用户
const editUser = ref({
  editKey: (route.query.editKey || '') as keyof UserType,
  currentValue: route.query.currentValue as string,
  editName: route.query.editName as string
});
const currentUser = ref<UserType | null>(null);
onMounted(async () => {
  const resp = await getCurrentUser();
  if (resp.status === 0 && resp.data) {
    currentUser.value = resp.data;
  } else {
    console.error('获取用户失败', resp.data);
    route.path({
      query:"/login"
    })
  }
})

const onSubmit = async () => {
  if (currentUser.value && editUser.value.editKey) {
    // 使用类型安全的赋值
    currentUser.value[editUser.value.editKey] = editUser.value.currentValue as unknown as UserType[keyof UserType];
    console.log(currentUser.value);
  }
  const resp = await myAxios.post('/user/update', {
    user: currentUser.value
  })
  if (resp.status === 0 && resp.data.data) {
    Toast.success("修改成功");
    router.back();
  } else {
    Toast.fail("修改失败");
  }
};
//修改用户
const value = ref([
  {url: `${editUser.value.currentValue}`},
]);
</script>
<template>
  <van-form @submit="onSubmit">
    <van-field v-if=" editUser.editName!=='头像'"
               v-model="editUser.currentValue"
               :name="editUser.editKey"
               :label="editUser.editName"
               :placeholder="`请输入${editUser.editName}`"
    />
    <van-field v-if=" editUser.editName==='头像'"
               :name="editUser.editKey"
               :label="editUser.editName">
      <template #input>
        <van-uploader v-model="value"/>
      </template>
    </van-field>
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>
<style scoped>
</style>